/* 
 * Author: anand
 * 
 */


#include "playlist_item.h"

dbhelper * playlist_item::_dbhelper = dbhelper::get_helper();

playlist_item::playlist_item(const playlist_item& orig) {
    _path = orig._path;
	_name = orig._name;
	_position = orig._position;
	_id = orig._id;
	_playcount = orig._playcount;
	_folder = orig._folder;
}


/*Default delete implementation, assume we are a file*/
void playlist_item::unlink(){
    
}

playlist_item::~playlist_item() {
   //DEBUG fprintf(stderr,"Playlist item destroyed %f \n",_position);
}

void playlist_item::save()
{
	if(!_folder.get_id())
	{
		_folder.save(_path.c_str());
	}
	if(!_id)
	{
		std::string sql = PLAYLISTITEM_GET_SQL;
		sql.replace(sql.find("?"),1,path_util::convert_to_string(_folder.get_id()));
		sql.replace(sql.find("?"),1,_name);
		result_set * result = _dbhelper->get_row_map(sql.c_str());
		if(result->size())
		{
			_id = atoi( (*(result->at(0)))["id"].c_str());
		}else
		{
			std::string savesql = PLAYLISTITEM_SAVE_SQL;
			_id = _dbhelper->get_id(PLAYLISTITEM_TABLE_NAME);
			_playcount = 0;
			savesql.replace(savesql.find("?"),1,path_util::convert_to_string(_id));
			savesql.replace(savesql.find("?"),1,path_util::convert_to_string(_folder.get_id()));
			savesql.replace(savesql.find("?"),1,_name);
			savesql.replace(savesql.find("?"),1,path_util::convert_to_string(_playcount));
			_dbhelper->raw_execute(savesql.c_str());
		}

	}else
	{
		std::string sql = PLAYLIST_UPDATE_SQL;
		sql.replace(sql.find("?"),1, path_util::convert_to_string(_playcount));
		_dbhelper->raw_execute(sql.c_str());
	}
	
}
